package com.wangsd.web.sys.service;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.util.MyBeanUtil;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.web.mqpay.service.CustomerService;
import com.wangsd.web.sys.entity.SysMenu;
import com.wangsd.web.sys.entity.SysRole;
import com.wangsd.web.sys.entity.SysUser;
import com.wangsd.web.sys.entity.SysUserRole;
import com.wangsd.web.sys.mapper.SysUserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SysUserService {

    @Resource
    private SysUserMapper mapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysCompanyService companyService;
    @Autowired
    private CustomerService customerService;


    public SysUser selectByLogin(String username, String password) {
        SysUser user = mapper.selectByLogin(username, password);
        if (user == null) {
            throw new BusinessException("账号密码错误");
        }
        if (user.isStatus()) {
            throw new BusinessException("该账号已被禁用");
        }
        String token = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        redisTemplate.opsForValue().set(token, user, 12, TimeUnit.HOURS);
        user.setToken(token);
        return user;
    }

    public List<SysUser> selectPage(SysUser queryObj, String code) {
        Query query = new Query();
        if (StringUtils.isNotBlank(queryObj.getRealName())) {
            query.like("t.real_name", queryObj.getRealName());
        }
        if (StringUtils.isNotBlank(queryObj.getUsername())) {
            query.like("t.username", queryObj.getUsername());
        }
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("t.code", code);
        }
        query.eq("t.type", queryObj.getType());
        if (queryObj.getType() == 1 || queryObj.getType() == 2) {//服务商
            query.join("join sys_company t2 on t.code = t2.code");
        } else if (queryObj.getType() == 3) { //客户(商圈)
            query.join("join customer t2 on t.code = t2.code");
        }
        List<String> column = Arrays.asList("t.*, t2.name as parentName");

        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        List<SysUser> list = MyBeanUtil.mapListToObjList(mapList, SysUser.class);
        return list;
    }

    /**
     * 获取登录用户权限
     *
     * @param loginUser
     * @return
     */
    public SysUser selectPermission(SysUser loginUser) {
        List<SysMenu> menuList = new ArrayList<>();
        if (loginUser.getType() == 99) {//超级管理员
            menuList = menuService.selectByAdmin();
        } else {
            List<SysRole> roleList = roleService.selectByUserId(loginUser.getId());
            for (SysRole role : roleList) {
                List<SysMenu> temp = menuService.selectByRoleId(role.getId());
                menuList.addAll(temp);
            }
        }
        List<String> keySing = menuList.stream().map(SysMenu::getKeySign).collect(Collectors.toList());
        loginUser.setMenuList(menuList);
        loginUser.setPermissionList(keySing);
        return loginUser;
    }

    /**
     * 根据parentCode查询所有用户
     * @param parentCode
     * @return
     */
    public List<SysUser> selectByParentCode(String parentCode) {
        Query query = new Query();
        query.eq("code", parentCode);
        return mapper.list(query);
    }

    @Transactional
    public void saveOrUpdate(SysUser entity) {
        SysUser user = this.selectByName(entity.getUsername(), entity.getId());
        if (user != null) {
            throw new BusinessException("登陆名称不能重复！");
        }
        if (entity.getId() != null) {
            roleService.removeRoleByUserId(entity.getId());
            mapper.updateIgnoreNull(entity);
        } else {
            mapper.saveIgnoreNull(entity);
        }

        if (entity.getRoleIds() != null) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            for (Long roleId : entity.getRoleIds()) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(entity.getId());
                userRole.setRoleId(roleId);
                sysUserRoleList.add(userRole);
            }
            if (sysUserRoleList.size() > 0) {
                roleService.saveBatch(sysUserRoleList);
            }
        }
    }

    public int delete(Long id) {
        return mapper.deleteById(id);
    }

    /**
     * 修改密码
     * @param oldPass
     * @param password
     * @param id
     * @return
     */
    public int updatePassword(String oldPass, String password, Long id) {
        SysUser user = mapper.getById(id);
        if (!user.getPassword().equals(oldPass)) {
            throw new BusinessException("原始密码不对");
        }
        user.setPassword(password);
        return mapper.updateIgnoreNull(user);
    }

    private SysUser selectByName(String name, Long id) {
        Query query = new Query();
        query.eq("username", name);
        if (id != null) {
            query.notEq("id", id);
        }
        return mapper.getByQuery(query);
    }
}
